<template>
	<view class="container">
		<!-- 顶部导航栏 -->
		<view class="header">
			<view class="header-left">
				<text class="system-title">水质监测系统</text>
				<text class="system-subtitle">Water Quality Monitoring System</text>
			</view>
			<view class="header-right">
				<text class="current-time">{{ currentTime }}</text>
				<text class="current-date">{{ currentDate }}</text>
			</view>
		</view>

		<!-- 主要内容区域 -->
		<scroll-view scroll-y class="main-content">
			<!-- 水质数据概览 -->
			<view class="water-quality-overview">
				<view class="quality-header">
					<text class="quality-title">水质监测数据</text>
					<view class="quality-level" :class="waterQualityLevel.level">
						<text class="level-text">{{ waterQualityLevel.level }}</text>
					</view>
				</view>
            <view class="quality-cards">
                <view class="quality-card" v-for="(item, index) in realtimeData" :key="index">
                    <view class="card-header">
                        <view class="card-left">
                            <view class="card-icon" :class="item.type">
                                <uni-icons :type="item.icon" size="22" color="#fff"></uni-icons>
                            </view>
                            <text class="card-label">{{ item.name }}</text>
                        </view>
                        <view class="card-status" :class="item.status"></view>
                    </view>
                    <view class="card-body">
                        <text class="card-value">{{ item.value }}<text class="unit">{{ item.unit }}</text></text>
                        <text class="card-trend" :class="item.trend > 0 ? 'up' : 'down'">
                            {{ item.trend > 0 ? '↑' : '↓' }} {{ Math.abs(item.trend) }}%
                        </text>
                    </view>
                </view>
            </view>
			</view>

			<!-- 设备状态统计 -->
			<view class="device-status">
				<view class="status-header">
					<text class="status-title">设备状态统计</text>
					<text class="status-subtitle">共{{ deviceStats.total }}台设备</text>
				</view>
				<view class="status-cards">
					<view class="status-card online">
						<text class="status-number">{{ deviceStats.online }}</text>
						<text class="status-label">在线</text>
					</view>
					<view class="status-card offline">
						<text class="status-number">{{ deviceStats.offline }}</text>
						<text class="status-label">离线</text>
					</view>
					<view class="status-card fault">
						<text class="status-number">{{ deviceStats.fault }}</text>
						<text class="status-label">故障</text>
					</view>
				</view>
			</view>

			<!-- 告警信息 -->
			<view class="alert-info">
				<view class="alert-header">
					<text class="alert-title">告警信息</text>
					<view class="alert-count">{{ alertStats.unhandled }}</view>
				</view>
				<view class="alert-list">
					<view class="alert-item" v-for="(alert, index) in recentAlerts" :key="index">
						<view class="alert-level" :class="alert.level"></view>
						<view class="alert-content">
							<text class="alert-text">{{ alert.title }}</text>
							<text class="alert-time">{{ formatTime(alert.time) }}</text>
						</view>
					</view>
				</view>
			</view>

			<!-- 功能菜单 -->
			<view class="function-menu">
				<view class="menu-title">功能菜单</view>
				<view class="menu-grid">
					<view class="menu-item" @click="navigateTo('/pages/monitor/monitor')">
						<view class="menu-icon monitor">
							<uni-icons type="eye" size="28" color="#ffffff"></uni-icons>
						</view>
						<text class="menu-text">实时监测</text>
					</view>
					<view class="menu-item" @click="navigateTo('/pages/map/map')">
						<view class="menu-icon map">
							<uni-icons type="location" size="28" color="#ffffff"></uni-icons>
						</view>
						<text class="menu-text">地图监控</text>
					</view>
					<view class="menu-item" @click="navigateTo('/pages/alert/alert')">
						<view class="menu-icon alert">
							<uni-icons type="sound" size="28" color="#ffffff"></uni-icons>
						</view>
						<text class="menu-text">告警管理</text>
					</view>
					<view class="menu-item" @click="navigateTo('/pages/analysis/analysis')">
						<view class="menu-icon analysis">
							<uni-icons type="bar-chart" size="28" color="#ffffff"></uni-icons>
						</view>
						<text class="menu-text">数据分析</text>
					</view>
					<view class="menu-item" @click="navigateTo('/pages/trace/trace')">
						<view class="menu-icon trace">
							<uni-icons type="search" size="28" color="#ffffff"></uni-icons>
						</view>
						<text class="menu-text">污染溯源</text>
					</view>
					<view class="menu-item" @click="navigateTo('/pages/message/message')">
						<view class="menu-icon message">
							<uni-icons type="chat" size="28" color="#ffffff"></uni-icons>
						</view>
						<text class="menu-text">消息中心</text>
					</view>
					<view class="menu-item" @click="navigateTo('/pages/pollution/pollution-prediction/pollution-prediction')">
						<view class="menu-icon pollution">
							<uni-icons type="home" size="28" color="#ffffff"></uni-icons>
						</view>
						<text class="menu-text">污染预测</text>
					</view>
					<view class="menu-item" @click="navigateTo('/pages/factory-analysis/factory-analysis')">
						<view class="menu-icon factory">
							<uni-icons type="flask" size="28" color="#ffffff"></uni-icons>
						</view>
						<text class="menu-text">化工厂分析</text>
					</view>
					<view class="menu-item" @click="navigateTo('/pages/settings/settings')">
						<view class="menu-icon settings">
							<uni-icons type="person" size="28" color="#ffffff"></uni-icons>
						</view>
						<text class="menu-text">我的</text>
					</view>
					<view class="menu-item" @click="navigateTo('/pages/AI/AI')">
						<view class="menu-icon monitor">
							<uni-icons type="eye" size="28" color="#ffffff"></uni-icons>
						</view>
						<text class="menu-text">水质分析</text>
					</view>
				</view>
			</view>
		</scroll-view>
	</view>
</template>

<script setup>
import { ref, onMounted, onUnmounted, computed } from 'vue'
import { useUserStore } from '@/stores/user.js'
import { BASE_URL } from '@/api/request.js'

// 使用用户状态管理
const userStore = useUserStore()

// 响应式数据
const currentTime = ref('')
const currentDate = ref('')

// 实时数据
const realtimeData = ref([
	{ name: 'pH值', value: 7.2, unit: '', icon: 'water', color: '#3498db', type: 'ph', trend: 1.2, status: 'normal' },
	{ name: '温度', value: 22.5, unit: '°C', icon: 'fire', color: '#e74c3c', type: 'temp', trend: -0.5, status: 'normal' },
	{ name: '浊度', value: 1.8, unit: 'NTU', icon: 'eye', color: '#9b59b6', type: 'turbidity', trend: 0.8, status: 'normal' }
])

let ws = null

// 设备统计
const deviceStats = ref({
	total: 18,
	online: 15,
	offline: 2,
	fault: 1
})

// 告警统计
const alertStats = ref({
	total: 12,
	unhandled: 3,
	handled: 9
})

// 最近告警
const recentAlerts = ref([
	{ title: '监测点003设备离线', time: new Date(), level: 'high' },
	{ title: '监测点004温度异常', time: new Date(Date.now() - 300000), level: 'medium' },
	{ title: '监测点002浊度超标', time: new Date(Date.now() - 600000), level: 'low' }
])

// 计算属性 - 水质等级
const waterQualityLevel = computed(() => {
	const phValue = realtimeData.value.find(item => item.type === 'ph')?.value || 7.2
	const temperature = realtimeData.value.find(item => item.type === 'temp')?.value || 22.5
	const turbidity = realtimeData.value.find(item => item.type === 'turbidity')?.value || 1.8

	let score = 0

	// pH值评分 (6.5-8.5为最佳)
	if (phValue >= 6.5 && phValue <= 8.5) {
		score += 25
	} else if (phValue >= 6.0 && phValue <= 9.0) {
		score += 15
	} else {
		score += 5
	}

	// 温度评分 (20-25°C为最佳)
	if (temperature >= 20 && temperature <= 25) {
		score += 25
	} else if (temperature >= 15 && temperature <= 30) {
		score += 15
	} else {
		score += 5
	}

	// 浊度评分 (越低越好)
	if (turbidity < 1000) {
		score += 25
	} else if (turbidity < 2000) {
		score += 15
	} else if (turbidity < 3000) {
		score += 10
	} else {
		score += 5
	}

	// 总分按三个指标等权重

	if (score >= 60) return { level: '优秀', color: '#27ae60' }
	if (score >= 45) return { level: '良好', color: '#f39c12' }
	if (score >= 30) return { level: '一般', color: '#e67e22' }
	return { level: '较差', color: '#e74c3c' }
})

// 页面加载
onMounted(() => {
	loadData()
	updateTime()
	// 每秒更新时间
	setInterval(updateTime, 1000)
	// 启用实时 WebSocket 联动
	initWebSocket()
})

onUnmounted(() => {
	if (ws) {
		ws.close()
		ws = null
	}
})

// 更新时间
const updateTime = () => {
	const now = new Date()
	const hours = now.getHours().toString().padStart(2, '0')
	const minutes = now.getMinutes().toString().padStart(2, '0')
	const month = (now.getMonth() + 1).toString().padStart(2, '0')
	const day = now.getDate().toString().padStart(2, '0')

	currentTime.value = `${hours}:${minutes}`
	currentDate.value = `${month}-${day}`
}

// 加载数据
const loadData = () => {
	// 模拟数据更新
	updateRealtimeData()
}

// 更新实时数据
const updateRealtimeData = () => {
	realtimeData.value.forEach(item => {
		// 模拟数据变化
		const variation = (Math.random() - 0.5) * 0.2
		item.value = Math.round((item.value + variation) * 10) / 10
		item.trend = (Math.random() - 0.5) * 5

		// 判断状态
		if (item.type === 'ph') {
			item.status = item.value >= 6.5 && item.value <= 8.5 ? 'normal' : 'warning'
		} else if (item.type === 'temp') {
			item.status = item.value >= 20 && item.value <= 25 ? 'normal' : 'warning'
		} else if (item.type === 'turbidity') {
			item.status = item.value < 3000 ? 'normal' : 'warning'
		}
	})
}

// 初始化WebSocket长连接（用于实时更新 ph/温度/浊度）
const initWebSocket = () => {
	try {
		const wsUrl = BASE_URL.replace('http', 'ws') + '/ws/water-quality'
		ws = new WebSocket(wsUrl)
		ws.onopen = () => {}
		ws.onmessage = (evt) => {
			try {
				const msg = JSON.parse(evt.data)
				applyRealtimeMessage(msg)
			} catch (e) {
				// 静默失败
			}
		}
		ws.onclose = () => {
			setTimeout(initWebSocket, 5000)
		}
		ws.onerror = () => {}
	} catch (e) {
		// 静默失败
	}
}

// 应用实时消息到UI
const applyRealtimeMessage = (msg) => {
	const mapping = {
		ph: 'phValue',
		temp: 'temperature',
		turbidity: 'turbidity'
	}
	realtimeData.value = realtimeData.value.map(item => {
		const key = mapping[item.type]
		if (key && typeof msg[key] === 'number') {
			const old = item.value
			item.value = Math.round(msg[key] * 10) / 10
			item.trend = Math.round((item.value - old) * 10) / 10
			// 状态判断与上面一致
			if (item.type === 'ph') {
				item.status = item.value >= 6.5 && item.value <= 8.5 ? 'normal' : 'warning'
			} else if (item.type === 'temp') {
				item.status = item.value >= 20 && item.value <= 25 ? 'normal' : 'warning'
			} else if (item.type === 'turbidity') {
				item.status = item.value < 3000 ? 'normal' : 'warning'
			}
		}
		return item
	})
}

// 格式化时间
const formatTime = (time) => {
	const date = new Date(time)
	const hours = date.getHours().toString().padStart(2, '0')
	const minutes = date.getMinutes().toString().padStart(2, '0')
	return `${hours}:${minutes}`
}

// 页面跳转
const navigateTo = (url) => {
	uni.navigateTo({ url })
}

</script>

<style lang="scss" scoped>
.container {
	height: 100vh;
	display: flex;
	flex-direction: column;
	background: #f5f7fa;
}

.header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 30rpx;
	background: #ffffff;
	border-bottom: 1rpx solid #e5e5e5;
	box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.header-left {
	display: flex;
	flex-direction: column;
}

.system-title {
	font-size: 36rpx;
	font-weight: bold;
	color: #2c3e50;
	margin-bottom: 5rpx;
}

.system-subtitle {
	font-size: 22rpx;
	color: #7f8c8d;
}

.header-right {
	display: flex;
	flex-direction: column;
	align-items: flex-end;
}

.current-time {
	font-size: 28rpx;
	font-weight: bold;
	color: #2c3e50;
}

.current-date {
	font-size: 20rpx;
	color: #7f8c8d;
}

.main-content {
	flex: 1;
	padding: 20rpx;
}

.water-quality-overview {
	background: #ffffff;
	border-radius: 12rpx;
	padding: 30rpx;
	margin-bottom: 20rpx;
	box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.08);
}

.quality-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 30rpx;
}

.quality-title {
	font-size: 32rpx;
	font-weight: bold;
	color: #2c3e50;
}

.quality-level {
	padding: 8rpx 20rpx;
	border-radius: 20rpx;
	background: #27ae60;

	&.excellent {
		background: #27ae60;
	}

	&.good {
		background: #f39c12;
	}

	&.average {
		background: #e67e22;
	}

	&.poor {
		background: #e74c3c;
	}
}

.level-text {
	font-size: 20rpx;
	color: #ffffff;
	font-weight: bold;
}

.quality-cards {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 20rpx;
}

.quality-card {
    padding: 22rpx;
    background: linear-gradient(180deg, #ffffff 0%, #f8fafc 100%);
    border-radius: 12rpx;
    position: relative;
    box-shadow: 0 4rpx 14rpx rgba(0, 0, 0, 0.06);
    border: 1rpx solid #eef2f7;
}

.card-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.card-left {
    display: flex;
    align-items: center;
    gap: 16rpx;
}

.card-icon {
    width: 48rpx;
    height: 48rpx;
    border-radius: 10rpx;
    display: flex;
    align-items: center;
    justify-content: center;

    &.ph { background: #3498db; }
    &.temp { background: #e74c3c; }
    &.turbidity { background: #9b59b6; }
    &.oxygen { background: #27ae60; }
}

.card-content {
	flex: 1;
}

.card-label {
    font-size: 24rpx;
    color: #556370;
    font-weight: 600;
}

.card-body {
    display: flex;
    align-items: baseline;
    justify-content: space-between;
    margin-top: 14rpx;
}

.card-value {
    font-size: 40rpx;
    font-weight: 700;
    color: #1f2d3d;
}

.unit {
    font-size: 20rpx;
    color: #7a8a99;
    margin-left: 6rpx;
}

.card-trend {
	font-size: 18rpx;
	font-weight: bold;

	&.up {
		color: #27ae60;
	}

	&.down {
		color: #e74c3c;
	}
}

.card-status {
    width: 12rpx;
    height: 12rpx;
    border-radius: 50%;

    &.normal { background: #27ae60; }
    &.warning { background: #f39c12; }
    &.danger { background: #e74c3c; }
}

.device-status {
	background: #ffffff;
	border-radius: 12rpx;
	padding: 30rpx;
	margin-bottom: 20rpx;
	box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.08);
}

.status-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 30rpx;
}

.status-title {
	font-size: 32rpx;
	font-weight: bold;
	color: #2c3e50;
}

.status-subtitle {
	font-size: 22rpx;
	color: #7f8c8d;
}

.status-cards {
	display: flex;
	justify-content: space-around;
}

.status-card {
	display: flex;
	flex-direction: column;
	align-items: center;
	padding: 20rpx;
	border-radius: 8rpx;
	min-width: 120rpx;

	&.online {
		background: #d5f4e6;
		border: 2rpx solid #27ae60;
	}

	&.offline {
		background: #f8f9fa;
		border: 2rpx solid #95a5a6;
	}

	&.fault {
		background: #fadbd8;
		border: 2rpx solid #e74c3c;
	}
}

.status-number {
	font-size: 36rpx;
	font-weight: bold;
	margin-bottom: 10rpx;

	&.online {
		color: #27ae60;
	}

	&.offline {
		color: #95a5a6;
	}

	&.fault {
		color: #e74c3c;
	}
}

.status-label {
	font-size: 22rpx;
	color: #7f8c8d;
}

.alert-info {
	background: #ffffff;
	border-radius: 12rpx;
	padding: 30rpx;
	margin-bottom: 20rpx;
	box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.08);
}

.alert-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 20rpx;
}

.alert-title {
	font-size: 32rpx;
	font-weight: bold;
	color: #2c3e50;
}

.alert-count {
	width: 40rpx;
	height: 40rpx;
	background: #e74c3c;
	border-radius: 50%;
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 20rpx;
	color: #ffffff;
	font-weight: bold;
}

.alert-list {
	display: flex;
	flex-direction: column;
	gap: 15rpx;
}

.alert-item {
	display: flex;
	align-items: center;
	padding: 15rpx;
	background: #f8f9fa;
	border-radius: 8rpx;
	border-left: 4rpx solid #e74c3c;
}

.alert-level {
	width: 12rpx;
	height: 12rpx;
	border-radius: 50%;
	background: #e74c3c;
	margin-right: 15rpx;
}

.alert-content {
	flex: 1;
}

.alert-text {
	font-size: 24rpx;
	color: #2c3e50;
	margin-bottom: 5rpx;
	display: block;
}

.alert-time {
	font-size: 20rpx;
	color: #7f8c8d;
}

.function-menu {
	background: #ffffff;
	border-radius: 12rpx;
	padding: 30rpx;
	box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.08);
}

.menu-title {
	font-size: 32rpx;
	font-weight: bold;
	color: #2c3e50;
	margin-bottom: 30rpx;
}

.menu-grid {
	display: grid;
	grid-template-columns: repeat(3, 1fr);
	gap: 20rpx;
}

.menu-item {
	display: flex;
	flex-direction: column;
	align-items: center;
	padding: 30rpx 20rpx;
	background: #f8f9fa;
	border-radius: 8rpx;
	transition: all 0.3s;

	&:active {
		transform: scale(0.95);
		background: #e9ecef;
	}
}

.menu-icon {
	width: 60rpx;
	height: 60rpx;
	border-radius: 12rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	margin-bottom: 15rpx;

	&.monitor {
		background: #3498db;
	}

	&.map {
		background: #27ae60;
	}

	&.alert {
		background: #e74c3c;
	}

	&.analysis {
		background: #9b59b6;
	}

	&.trace {
		background: #f39c12;
	}

	&.message {
		background: #e67e22;
	}

	&.pollution {
		background: #8e44ad;
	}

	&.factory {
		background: #e67e22;
	}

	&.settings {
		background: #95a5a6;
	}
}

.menu-text {
	font-size: 22rpx;
	color: #2c3e50;
	text-align: center;
	font-weight: 500;
}

</style>

